package com.yangyang.dingnote;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.button.MaterialButton;

public class EditNoteFragment extends Fragment {

    private EditText titleEditText;
    private EditText contentEditText;
    private Note note;
    private ClipboardManager clipboardManager;
    private NoteDatabaseHelper databaseHelper;
    private boolean isNewNote = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        clipboardManager = (ClipboardManager) requireActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        databaseHelper = new NoteDatabaseHelper(requireContext());
    }

    //创建并返回 Fragment 的视图层级
    //在 onCreate() 之后
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_edit_note, container, false);

        // 初始化视图
        titleEditText = view.findViewById(R.id.titleEditText);
        contentEditText = view.findViewById(R.id.contentEditText);

        // 默认将焦点和光标放在内容编辑框
        contentEditText.requestFocus();

        // 获取传递的数据
        Bundle args = getArguments();
        if (args != null && args.containsKey("note")) {
            note = args.getParcelable("note");
            if (note != null) {
                titleEditText.setText(note.getTitle());
                contentEditText.setText(note.getContent());
                // 将光标移动到内容末尾
                contentEditText.setSelection(contentEditText.getText().length());

                // 判断是否是粘贴操作创建的新笔记（ID为-1表示新笔记）
                isNewNote = note.getId() == -1;
                //isNewNote = args.getBoolean("isNewNote", true); // 默认true更安全
            }
        } else {
            // 新建笔记
            note = new Note("", "");
            isNewNote = true;
        }

//        // 设置菜单项点击监听
//        MaterialToolbar toolbar = view.findViewById(R.id.toolbar);
//        toolbar.setNavigationOnClickListener(v -> {
//            // 返回上一页面
//            Navigation.findNavController(view).navigateUp();
//        });
//
//        // 处理菜单点击（复制/粘贴）
//        toolbar.setOnMenuItemClickListener(item -> {
//            int id = item.getItemId();
//            if (id == R.id.menu_copy) {
//                handleCopy();
//                return true;
//            } else if (id == R.id.menu_paste) {
//                handlePaste();
//                return true;
//            }
//            return false;
//        });

        // 设置 Toolbar
        ImageButton btnBack = view.findViewById(R.id.btn_back);
        MaterialButton btnCopy = view.findViewById(R.id.btn_copy);
        MaterialButton btnPaste = view.findViewById(R.id.btn_paste);

        // 绑定返回按钮事件
        btnBack.setOnClickListener(v -> {
            Navigation.findNavController(view).navigateUp();
        });

        // 绑定复制按钮
        btnCopy.setOnClickListener(v -> {
            handleCopy();
        });
        // 绑定粘贴按钮
        btnPaste.setOnClickListener(v -> {
            handlePaste();
        });
        return view;
    }

    private void handleCopy() {
        String textToCopy = contentEditText.getText().toString();
        if (!textToCopy.isEmpty()) {
            ClipData clip = ClipData.newPlainText("Note Content", textToCopy);
            clipboardManager.setPrimaryClip(clip);
            Toast.makeText(getActivity(), "已复制到剪贴板", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity(), "没有内容可复制", Toast.LENGTH_SHORT).show();
        }
    }

    private void handlePaste() {
        if (clipboardManager.hasPrimaryClip()) {
            ClipData.Item item = clipboardManager.getPrimaryClip().getItemAt(0);
            String clipboardText = item.getText().toString();
            //contentEditText.getText().insert(contentEditText.getSelectionStart(), clipboardText);
            // 获取当前光标位置
            int cursorPosition = contentEditText.getSelectionStart();
            // 在光标位置插入剪贴板内容
            contentEditText.getText().insert(cursorPosition, clipboardText);
            // 将光标移动到插入文本的末尾
            contentEditText.setSelection(cursorPosition + clipboardText.length());
        } else {
            Toast.makeText(getActivity(), "剪贴板为空", Toast.LENGTH_SHORT).show();
        }
    }

    //在视图创建完成后初始化控件和逻辑
    //在 onCreateView() 之后
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        MaterialToolbar toolbar = view.findViewById(R.id.toolbar);
        toolbar.setNavigationOnClickListener(v -> {
            Navigation.findNavController(view).navigateUp();
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        // 保存当前编辑的内容
        saveNote();
    }

    private void saveNote() {
        String title = titleEditText.getText().toString();
        String content = contentEditText.getText().toString();
        if (note == null) {
            note = new Note(title, content);
        } else {
            note.setTitle(title);
            note.setContent(content);
        }
        if (isNewNote) {
            if (!title.isEmpty() || !content.isEmpty()) {
                note.setTitle(title);
                note.setContent(content);
                databaseHelper.addNote(note);
            }
        } else {
            note.setTitle(title);
            note.setContent(content);
            databaseHelper.updateNote(note);
        }
        // 返回上一页面
        Navigation.findNavController(requireView()).navigateUp();
    }
}
